//
//  RepeatFetch.swift
//  pgy
//
//  Created by vsccw on 2018/12/28.
//  Copyright © 2018 vsccw.com. All rights reserved.
//

import UIKit

import RxSwift
import RxCocoa

class RepeatFetch {
  
  static let shared = RepeatFetch()
  
  private let queueName = "com.vsccw.apps.repeatFetch"
  
  private var disposeBag = DisposeBag()
  
  private var timerObservable: Disposable?
  
  init() {
    resume()
    
    NotificationCenter.default.rx
      .notification(UIApplication.didEnterBackgroundNotification)
      .subscribe(onNext: { [weak self] (_) in
        self?.stop()
        print(">>>> background")
      }).disposed(by: disposeBag)
    
    NotificationCenter.default.rx
      .notification(UIApplication.willEnterForegroundNotification)
      .subscribe(onNext: { [weak self] (_) in
        self?.resume()
        print(">>>> foreground")
      }).disposed(by: disposeBag)
  }
  
  func resume() {
    self.timerObservable = Observable<Int>
      .interval(1 * 60, scheduler: SerialDispatchQueueScheduler(internalSerialQueueName: queueName))
      .subscribe(onNext: { (count) in
        print(">>>> timer \(count)")
      })
    disposeBag.insert(timerObservable!)
  }
  
  func stop() {
    self.timerObservable?.dispose()
  }
}
